import time

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from common.Utils import BlogDriver


# 测试博客编辑区
class BlogEdit:
    url=''
    driver=''
    def __init__(self):
        self.url = 'http://127.0.0.1:58080/index.html'
        self.driver = BlogDriver.driver
        self.driver.get(self.url)

    # 测试登录状态下编辑区
    def EditTestByLogin(self):

        # 点击 发布帖子按钮 跳转到编辑界面
        self.driver.find_element(By.CSS_SELECTOR,"#bit-forum-content > div.page-header.d-print-none > div > div > div.col-auto.ms-auto.d-print-none > div > a.btn.btn-primary.d-none.d-sm-inline-block.article_post").click()
        # # 等待新页面完全加载
        # WebDriverWait(self.driver, 10).until(
        #     EC.presence_of_element_located((By.CSS_SELECTOR, "#article_post_title"))
        # )
        time.sleep(3)

        # 板块选择
        dropdown = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "#article_post_borad"))
        )
        dropdown.click()

        option = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "#article_post_borad > option:nth-child(2)"))
        )

        option.click()

        time.sleep(3)
        # 输入标题
        self.driver.find_element(By.CSS_SELECTOR,"#article_post_title").send_keys("自动化测试输入")

        # 输入内容
        # self.driver.find_element(By.CSS_SELECTOR,"#edit-article > textarea.editormd-html-textarea").send_keys("自动化输入内容")
        # 点击激活编辑器
        editor_container = self.driver.find_element(By.CSS_SELECTOR, ".editormd")
        editor_container.click()

        # 通过ActionChains输入
        # from selenium.webdriver.common.action_chains import ActionChains
        ActionChains(self.driver).send_keys("自动化输入内容").perform()

        time.sleep(2)
        # 点击提交 发布 有可能被挡住了 通过JavaScript直接点击（绕过遮挡）
        submit = self.driver.find_element(By.CSS_SELECTOR, "#article_post_submit")
        self.driver.execute_script("arguments[0].click();", submit) # 通过JavaScript直接点击（绕过遮挡） execute_script

        # 添加屏幕截图
        BlogDriver.getScreeShot()

        # 检测发布是否成功
        actual = self.driver.find_element(By.CSS_SELECTOR,"#artical-items-body > div:nth-child(1) > div > div.col > div.text-truncate > a").text
        assert actual == "自动化测试输入"
